import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoWiget extends StatefulWidget {
  String videoUrl;

  VideoWiget({@required this.videoUrl});

  @override
  _VideoWigetState createState() => _VideoWigetState();
}

class _VideoWigetState extends State<VideoWiget> {
  VideoPlayerController _controller;
  Future _initializeVideoPlayerFuture;

  @override
  void initState() {
    _controller = VideoPlayerController.network(widget.videoUrl);
    _controller.setLooping(false);
    _initializeVideoPlayerFuture = _controller.initialize();
    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: _initializeVideoPlayerFuture,
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          if (snapshot.connectionState == ConnectionState.done) {
            return WillPopScope(
              // ignore: missing_return
              onWillPop: () {
                if (_controller.value.isPlaying) {
                  _controller.pause();
                }
              },
              child: GestureDetector(
                onTap: () {
                  if (_controller.value.isPlaying) {
                    _controller.pause();
                  } else {
                    _controller.play();
                  }
                },
                child: Stack(
                  children: [
                    AspectRatio(
                      // aspectRatio: 16 / 9,
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                    _controller.value.isPlaying
                        ? Container()
                        : Positioned(
                            child: Icon(
                            Icons.play_circle_fill,
                            color: Colors.grey,
                            size: 40,
                          )),
                  ],
                ),
              ),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        });
  }
}
